package iamdev.me.ytds.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * Title: JSONUtils.java
 * Copyright: Copyright (C) 2002 - 2018 GuangDong Eshore Technology Co. Ltd
 * Company: 广东亿迅科技有限公司 IT互联网部
 *
 * @author zxc
 * @time 2018/4/24 17:45
 */


public class JSONUtils {

    public static JSONObject getJSONObject(String path, JSONObject jsonObject){
        //a.b.c[0].
        String [] pathArray = path.split("\\.");
        JSONObject  result =jsonObject;
        for(int i=0;i<pathArray.length;i++){
            result=result.getJSONObject(pathArray[i]);
            if(result==null){
                return null;
            }
        }
        return result;
    }

    public static JSONObject getJSONObject(String path, String s){
        JSONObject jsonObject = JSON.parseObject(s);
        String [] pathArray = path.split("\\.");
        JSONObject  result =jsonObject;
        for(int i=0;i<pathArray.length;i++){
            result=result.getJSONObject(pathArray[i]);
            if(result==null){
                return null;
            }
        }
        return result;
    }

    public static JSONArray getJSONArray(String path, JSONObject jsonObject){
        //a.b.c[0].
        String [] pathArray = path.split(".");
        JSONObject  result =jsonObject;
        for(int i=0;i<pathArray.length;i++){
            if(i==pathArray.length-1){
                return result.getJSONArray(pathArray[i]);
            }
            result=result.getJSONObject(pathArray[i]);
        }
        return null;
    }
}
